/*
    This file is part of FSJController.

    FSJController is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    FSJController is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with FSJController.  If not, see <http://www.gnu.org/licenses/>.
*/

package de.qsc.fsjcontroller;

/**
 * Simple Dialplan Iterator<br>
 * <br>
 * {Application, Arguments} <br>
 * <br>
 * use like this: <br>
 * <br>
 * <code>
 *  new Dialplan(this, new String[][]{ <br>
                {"set", "call_timeout=60"}, <br>
                {"set", "ringback=${de-ring}"}, <br>
    }); <br>
    </code>
 * 
 * @author Andreas Mager <ama@qsc.de>
 * 
 */
public class FSDialplan {
 
    private Object[] transitionMatrix;
    private int step = 0;
    private String[][] args;
    private FSChannel channel;

    /**
     * 
     * @param channel
     *            the freeswitch channel
     * @param args
     *            a list of String arrays. To avoid errors create arrays with two Strings
     *            {Application, Arguments}
     */
    public FSDialplan(FSChannel channel, String[]... args) {
        this.args = args;
        this.channel = channel;
        transitionMatrix = new Object[args.length +1];
    }

    public Object getState() {
        if (this.transitionMatrix != null && this.transitionMatrix.length != 0) {
            for(int i = step; i >= 0; i--){
                if (transitionMatrix[i] != null){
                    return transitionMatrix[i];
                }
            }
        } 
        return new Integer(step);  
    }


    public void update(String[][] args){
        step = 0;
        this.args = args;
    }
    
    public Object[] getTransitionMatrix() {
        return transitionMatrix;
    }

    
    public void setTransition(int step, Object state){
        this.transitionMatrix[step] = state;
    }
    
    public void removeTransition(int step){
        this.transitionMatrix[step] = null;
    }
    
    
    public void setTransitionMatrix(Object[] transitionMatrix) {
        this.transitionMatrix = transitionMatrix;
    }

    
    /**
     * 
     * @return true if there some more to do
     */
    public boolean hasNext() {
        return args.length > step;
    }

    /**
     * executes the next command on the channel
     */
    public void next() {
        if (args[step].length> 0 && !args[step][0].isEmpty()) {
            channel.runApplication(args[step][0], args[step][1]);
        }
        step++;
    }

}
